<template>
  <div>
    <div class="">
      <div class="color-222 padding-tb10 bg-dd font-s12 padding-l margin-b">添加案例</div>
      <el-form class="padding-l" :rules="rules" ref="postForm" :model="postForm" label-width="180px" v-loading="listLoading">
        <el-form-item label="选择平台：" prop="companyId">
          <el-select @change="selectChange" v-model="postForm.companyId" filterable placeholder="请选择平台" v-loading="listLoading" clearable>
            <el-option
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.mpName"
              :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二维码地址：" prop="qrcodeImg">
          <el-input v-model="postForm.qrcodeImg" placeholder="" style="width: 350px" disabled="true"></el-input>
            <el-button @click="getQrCode()" :disabled="postForm.qrcodeImg!=''">获取二维码地址</el-button>
            <div>
             <img :src="qrCode" alt="" height="130px" width="130px" v-if="qrCode" style="margin-top:5px">
            </div>
        </el-form-item>
        <!-- <el-form-item style="width:750px;" label="头像:" prop="uploader" required>
           <el-upload
          ref="avatarUpload"
          name="avatar"
          :action="imageUploadUrl"
          list-type="picture"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :on-remove="handleAvatarRemove"
          :file-list="avatarList"
          :limit="1"
          :auto-upload="false"
          style="width: 520px">
          <el-button slot="trigger" size="small" type="primary" @click="beforeChoose">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitAvatarUpload">上传到服务器
          </el-button>(建议头像尺寸80px*80px,或者宽高比例为1：1)
        </el-upload>
        </el-form-item> -->
        <el-form-item label="头像(宽80*高80)：" prop="uploader" required>
          <image-component class="fl" :image="postForm.avatar" :width="'80px'" :height="'80px'"></image-component>
          <el-button  class="fl el-btn" size="small" icon="upload" style="bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">
            更换图片
          </el-button>
          <image-cropper :width="80" :height="80" :url="imageUploadUrl" @close='closeImageCropper'
                        @crop-upload-success="cropSuccess" langType="zh"
                        :key="imagecropperKey" v-show="imagecropperShow"></image-cropper>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="postForm.sort" placeholder="请输入排序号" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>
          <el-button type="info" @click="close">关闭</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getAllCompanyList, toGetQrCode, getCaseDetail, saveCase } from '@/api/extra'
import imageComponent from '@/components/imageComponent'
import ImageCropper from '@/components/ImageCropper'
export default {
  components: {
    imageComponent,
    ImageCropper
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: {
        companyId: null,
        avatar: ' ',
        qrcodeImg: '',
        sort: 0,
        caseId: 0
      },
      qrCode: null,
      companyList: {},
      listLoading: false,
      imageUploadUrl: process.env.BASE_API + '/common/successCase/imageUpload',
      rules: {
        companyId: [
          { required: true, message: '请选择平台', trigger: 'change' }
        ],
        qrcodeImg: [
          { required: true, message: '请获取二维码地址', trigger: 'blur' }
        ]
      },
      imagecropperShow: false,
      imagecropperKey: 0
    }
  },
  created() {
    this.getCompanyList()
    if (this.isEdit) {
      this.getCaseInfo()
    }
  },
  methods: {
    selectChange(option) {
      if (option.companyId != this.postForm.companyId) {
        this.postForm.qrcodeImg = ''
      }
    },
    getCompanyList() {
      this.listLoading = true
      getAllCompanyList(this.listQuery).then(res => {
        this.companyList = res.data.data
        this.listLoading = false
      })
        .catch(err => {
          console.log(err)
        })
    },
    getCaseInfo() {
      this.listLoading = true
      getCaseDetail(this.$route.params.caseId).then(res => {
        console.log('成功案例', res)
        this.postForm = res.data.data
        this.qrCode = res.data.data.qrcodeImg
        // if (this.postForm.avatar) {
        //   this.avatarList = [{ url: this.postForm.avatar }]
        // }
        this.listLoading = false
      })
        .catch(err => {
          console.log(err)
        })
    },
    getQrCode(companyId) {
      if (this.postForm.companyId) {
        toGetQrCode(this.postForm.companyId).then(res => {
          this.postForm.qrcodeImg = res.data.data.qrCodeUrl
          this.qrCode = res.data.data.qrCodeUrl
        })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.$message.error('请先选择平台!')
      }
    },
    // handleAvatarSuccess(response, file, fileList) {
    //   if (response.statusCode == 200) {
    //     this.postForm.avatar = response.data.imageUrl
    //     this.$message({
    //       message: '上传成功!',
    //       type: 'info'
    //     })
    //   } else {
    //     this.$message({
    //       message: '上传失败，请稍候再试!',
    //       type: 'info'
    //     })
    //   }
    // },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg'
    //   const isLt2M = file.size / 1024 / 1024 < 2

    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!')
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!')
    //   }
    //   return isJPG && isLt2M
    // },
    // handleBeforeUpload() {

    // },
    // 图片裁剪
    closeImageCropper() {
      this.imagecropperShow = false
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.postForm.avatar = resData.data.imageUrl
    },
    close() {
      this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
        const latestView = views.slice(-1)[0]
        console.log(latestView)
        if (latestView) {
          this.$router.push(latestView.path)
        } else {
          this.$router.push('/')
        }
      })
    },
    // submitAvatarUpload() {
    //   this.$refs.avatarUpload.submit()
    // },
    // handleAvatarRemove(file, fileList) {
    //   this.postForm.avatar = ''
    //   this.avatarList = []
    // },
    submitForm() {
      if (this.postForm.companyId == '' || this.postForm.companyId == null) {
        this.$message({
          type: 'warning',
          message: ' 平台必须选择! '
        })
        return
      }
      if (this.postForm.qrcodeImg == '') {
        this.$message({
          type: 'warning',
          message: ' 二维码必须获取! '
        })
        return
      }
      if (!this.postForm.avatar) {
        this.$message({
          type: 'warning',
          message: ' 头像必上传! '
        })
        return
      }
      saveCase(this.postForm)
        .then(res => {
          this.$message({
            type: 'success',
            message: ' 保存成功! '
          })
          this.close()
        })
        .catch(err => {
          console.log(err)
        })
    },
    beforeChoose() {
      if (this.postForm.avatar != '') {
        this.$message.warning('请先清除已有图片再上传新图')
        return
      }
    }
  }
}
</script>
<style scoped>
  .inviteCardDetail {
    height: 550px;
    background: #fff;
    position: fixed;
    left: 25%;
    right: 25%;
    bottom: 15%;
    top: 5%;
    z-index: 120;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
